package soul.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * com.kashuo.crm.utils 上海卡说 zdcrm-ws
 *
 * @author yangyincong [yangyincong@kashuo.com] create on 2016-07-27 10:03
 * @version 1.0
 */
@Lazy(false)
@Component
public class ThreadUtils {

    private static ThreadPoolHolder THREAD_HOLDER;

    @Autowired
    public void init(ThreadPoolHolder holder) {
        THREAD_HOLDER = holder;
    }


    /**
     * 执行新的线程
     *
     * @param runnable
     */
    public static void run(Runnable runnable) {
        THREAD_HOLDER.run(runnable);
    }

    @Component
    public static class ThreadPoolHolder {
        private static volatile ThreadPoolHolder instance;

        private static volatile ExecutorService executorService;

        static {
            executorService = Executors.newCachedThreadPool();
        }

        private ThreadPoolHolder() {
        }

        public static ThreadPoolHolder getInstance() {
            if (null == instance) {
                synchronized (ThreadPoolHolder.class) {
                    if (null == instance) {
                        instance = new ThreadPoolHolder();
                    }
                }
            }
            return instance;
        }

        private void run(Runnable cmd) {
            executorService.execute(cmd);
        }

        public void close() {
            if (null != executorService && !executorService.isShutdown()) {
                executorService.shutdown();
            }
        }
    }
}
